package com.jxs.android.weixi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.KeyboardUtil;
import com.jxs.android.util.StringUtils;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TermView;
import com.jxs.android.weiget.TopBar;
import com.jxs.android.weixi.data.TermInfo;
import com.telecom.weixi.R;

public class Search_Of_Term extends AbstractActivity implements OnClickListener, TermView.LoadingDataListener {

	private ImageButton search_phone_btn;
	private int PAGE_SIZE = 13;
	private int currentPage = 1;
	private String searchNbr = "";

	private TermView termView;
	private EditText search_phone;
	private TopBar topBar;
	private LinearLayout container;
	private BuLoadingDailog buLoadingDailog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.bu_search_term_view);
		container = (LinearLayout) findViewById(R.id.test_container);
		search_phone_btn = (ImageButton) findViewById(R.id.bu_search_phone_btn);
		search_phone = (EditText) findViewById(R.id.bu_search_phone);
		search_phone_btn.setOnClickListener(this);
		buLoadingDailog = new BuLoadingDailog(this);
	}

	@Override
	public void onClick(View v) {
		currentPage = 1;
		if (container.getChildCount() != 0) {
			container.removeAllViews();
		}
		buLoadingDailog.showLoading(R.string.prompt_loading);
		loadingTermInfo(currentPage);
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarLogic(topBar);
		this.topBar = topBar;
		topBarReturn(topBar);
		topBar.hindBtn();
		topBar.setTitle(R.string.term_search);
	}

	@Override
	public void loadingData(int currentPage) {
		loadingTermInfo(currentPage);
	}

	private void loadingTermInfo(final int currentPage) {
		searchNbr = "";
		searchNbr = search_phone.getEditableText().toString();
		if (StringUtils.isEmpety(searchNbr)) {
			errorMsgPop(R.string.error_not_input_number);
			return;
		}
		if (KeyboardUtil.isImeShow(this)) {
			KeyboardUtil.hideIme(this);
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				initTermInfo(WeixiApplication.getApplication().getUserId(), searchNbr, PAGE_SIZE, currentPage);
			}
		}).start();
	}

	private void initTermInfo(String userId, final Object... params) {
		String wsdl_url = WeixiApplication.WSDL_URL;// wsdl
		String namespace = WeixiApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getTerminalInfodetail";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("userId", userId);
		request.addProperty("acc_nbr", params[0].toString());
		request.addProperty("pageSize", Integer.valueOf(params[1].toString()));
		request.addProperty("pageNo", Integer.valueOf(params[2].toString()));
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response, params);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}
		});
	}

	private void paser(SoapObject soapObject, Object... params) {
		if (null != soapObject) {
			Message msg = new Message();
			msg.what = UPDATE_LIST_UI;
			msg.obj = paserData(soapObject, params);
			handler.sendMessage(msg);
		} else {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = "无数据返回！";
			handler.sendMessage(msg);
		}
	}

	private Object paserData(SoapObject retMsgObject, Object... params) {
		List<TermInfo> tems = new ArrayList<TermInfo>();
		if (null != retMsgObject) {
			for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
				TermInfo termInfo = new TermInfo();

				termInfo.setItem_index(SoapUtil.getValue(taskBeanObject, "pos"));
				String content = SoapUtil.getValue(taskBeanObject, "content");
				String conts[] = content.split(":");
				if (null != conts && conts.length == 2) {
					termInfo.setItem_content_left(conts[0]);
					termInfo.setItem_content_center(conts[1]);
				} else {
					termInfo.setItem_content_center(conts[0]);
				}
				termInfo.setItem_content_right(SoapUtil.getValue(taskBeanObject, "register_time"));

				tems.add(termInfo);
			}
		}
		return tems;
	}

	private final int UPDATE_LIST_UI = 0x101;
	private final int ERROR_MSG = 0x1013;
	private final int TO_LOGIN = 0x1019;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_LIST_UI) {
				updateList(msg);
			} else if (msg.what == ERROR_MSG) {
				if (null != buLoadingDailog && buLoadingDailog.isShowing()) {
					buLoadingDailog.dismiss();
				}
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			}
		}
	};

	private void initTable(List<TermInfo> infos) {
		termView = new TermView(this);
		termView.setDataListener(this);
		termView.initTitle("序号", "终端厂商", "手机终端型号", "注册日期");

		boolean flag = false;
		if (currentPage == 1) {
			if (infos.size() < 1) {
				termView.setEmptyVisibility(View.VISIBLE);
				termView.getLoadMoreButton().setEnabled(false);
			}
			if (infos.size() < PAGE_SIZE) {
				flag = true;
				for (int i = infos.size(); i < PAGE_SIZE; i++) {
					infos.add(new TermInfo());
				}
			}
		}
		termView.setTermInfos(infos);
		if ((infos.size() < PAGE_SIZE) || flag) {
			termView.getLoadMoreButton().setText("数据已全部获取完毕");
			termView.getLoadMoreButton().setEnabled(false);
		} else {
			termView.getLoadMoreButton().setText("查看更多...");
			currentPage++;
			termView.setCurrentPage(currentPage);
		}

		container.addView(termView);
	}

	private void updateList(Message msg) {
		if (null != buLoadingDailog && buLoadingDailog.isShowing()) {
			buLoadingDailog.dismiss();
		}
		@SuppressWarnings("unchecked")
		List<TermInfo> infos = (List<TermInfo>) msg.obj;

		topBar.setSubTitle(searchNbr);
		if (container.getChildCount() == 0 && currentPage == 1) {
			initTable(infos);
		} else {
			termView.setEmptyVisibility(View.GONE);
			termView.getLoadMoreButton().setEnabled(true);
			if (currentPage == 1) {
				if (infos.size() < 1) {
					termView.setEmptyVisibility(View.VISIBLE);
					termView.getLoadMoreButton().setEnabled(false);
				}
			}
			termView.setTermInfos(infos);
			if ((infos.size() < PAGE_SIZE)) {
				termView.getLoadMoreButton().setText("数据已全部获取完毕");
				termView.getLoadMoreButton().setEnabled(false);
			} else {
				termView.getLoadMoreButton().setText("查看更多...");
				currentPage++;
				termView.setCurrentPage(currentPage);
			}
		}
	}

}
